﻿// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using Coding4Fun.Chair.Robot;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

using Color = System.Windows.Media.Color;
using Timer = System.Timers.Timer;

namespace Coding4Fun.Chair.Diagnostic
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		Timer _timer;
		Jellybean _jellybean;
		MotorController _comRightSide;
		MotorController _comLeftSide;

	    const int ComLeftSidePortNumber = 5;
	    const int ComRightSidePortNumber = 10;

		public MainWindow()
		{
			InitializeComponent();

			/*******************************************
            * 
            * DECLARE ROBOT OBJECT HERE
            * 
            * ****************************************/
		}

		double _leftHor;
		double _leftVert;
		double _rightHor;
		double _rightVert;
		bool _isConnected;

		readonly SolidColorBrush _red = new SolidColorBrush(Color.FromArgb(255, 220, 20, 60));
		readonly SolidColorBrush _green = new SolidColorBrush(Color.FromArgb(255, 191, 255, 0));

		void timerTick(object sender, ElapsedEventArgs e)
		{
			var state = GamePad.GetState(PlayerIndex.One);

			_isConnected = state.IsConnected;

			var aPressed = false;
			var bPressed = false;
            var yPressed = false;

			if (_isConnected)
			{
				_leftHor = state.ThumbSticks.Left.X;
				_leftVert = state.ThumbSticks.Left.Y;
				_rightHor = state.ThumbSticks.Right.X;
				_rightVert = state.ThumbSticks.Right.Y;
				aPressed = state.Buttons.A == ButtonState.Pressed;
				bPressed = state.Buttons.B == ButtonState.Pressed;
                yPressed = state.Buttons.Y == ButtonState.Pressed;

                if (_jellybean != null)
                    _jellybean.Drive(_leftVert, _leftHor, _rightVert, _rightHor);

                if (_comRightSide != null)
                    _comRightSide.SetMotorSpeed((int)(_leftVert * 1000), (int)(_leftHor * 1000));

                if (_comLeftSide != null)
                    _comLeftSide.SetMotorSpeed((int)(_rightVert * 1000), (int)(_rightHor * 1000));
			}

			Dispatcher.BeginInvoke(new ThreadStart(() =>
			{
				ControllerStatus.Text = (_isConnected) ? "Connected" : "Not Connected";
				ControllerStatus.Foreground = (_isConnected) ? _green : _red;

				if (!_isConnected)
					return;

				LeftThumbstick.HorizontalValue = _leftHor;
				LeftThumbstick.VerticalValue = _leftVert;
				RightThumbstick.HorizontalValue = _rightHor;
				RightThumbstick.VerticalValue = _rightVert;
				IsAPressed = aPressed;
				IsBPressed = bPressed;
                IsYPressed = yPressed;
			}));
		}



        public bool IsYPressed
        {
            get { return (bool)GetValue(IsYPressedProperty); }
            set { SetValue(IsYPressedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsYPressed.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsYPressedProperty =
            DependencyProperty.Register("IsYPressed", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false, OnButtonPressChanged));

        public bool IsAPressed
		{
			get { return (bool)GetValue(IsAPressedProperty); }
			set { SetValue(IsAPressedProperty, value); }
		}

		// Using a DependencyProperty as the backing store for IsAPressed.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty IsAPressedProperty =
			DependencyProperty.Register("IsAPressed", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false, OnButtonPressChanged));

		public bool IsBPressed
		{
			get { return (bool)GetValue(IsBPressedProperty); }
			set { SetValue(IsBPressedProperty, value); }
		}

		// Using a DependencyProperty as the backing store for IsBPressed.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty IsBPressedProperty =
			DependencyProperty.Register("IsBPressed", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false, OnButtonPressChanged));


		private static void OnButtonPressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var sender = (MainWindow)d;

			if (sender == null || !(bool)e.NewValue)
				return;

			if (e.Property == IsAPressedProperty)
				sender._jellybean.InclineFootrest();
			else if (e.Property == IsBPressedProperty)
				sender._jellybean.DeclineFootrest();
            else if (e.Property == IsYPressedProperty)
                sender._jellybean.ToggleFootrest();
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			if (_timer != null)
				_timer.Dispose();

			if (_jellybean != null)
			{
				_jellybean.Dispose();
				_jellybean = null;
			}

			if (_comRightSide != null)
			{
				_comRightSide.Dispose();
				_comRightSide = null;
			}

			if (_comLeftSide != null)
			{
				_comLeftSide.Dispose();
				_comLeftSide = null;
			}

			if (rightSideCom.IsSelected)
			{
                _comRightSide = new MotorController(ComRightSidePortNumber);
				_comRightSide.Open();
			}

			else if (leftSideCom.IsSelected)
			{
                _comLeftSide = new MotorController(ComLeftSidePortNumber);
				_comLeftSide.Open();
			}
			else if (Jelly.IsSelected)
			{
                _jellybean = new Jellybean(ComLeftSidePortNumber, ComRightSidePortNumber, true);
                _jellybean.MaxThrottle = 1;
                _jellybean.AllowedMovementArea = .2;
			}

			_timer = new Timer(33);
			_timer.Elapsed += timerTick;
			_timer.Start();
		}
	}
}
